const puppeteer = require("puppeteer");

class Browser {
  async init() {
    this.browser = await puppeteer.launch({
      executablePath:
        "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
      headless: true, // 修改为 false 可以看到浏览器执行过程
      // slowMo: 20,
      defaultViewport: {
        width: 0,
        height: 0,
      },
    });
  }

  async check() {
    if (!this.browser) {
      await this.init();
    }
  }

  async capture(keywords) {
    await this.check();

    const page = await this.browser.newPage();

    await page.setViewport({
        width: 1920,
        height: 1080
    })

    await page.goto('https://www.beijing-time.org/shizhong.html', {
        waitUntil: 'networkidle2'
    });
    // await page.type("#kw", keywords); // 在搜索框中输入 "puppeteer"
    // await page.keyboard.press("Enter"); // 按下回车键

    // await page.waitForSelector("#content_left"); // 等待搜索结果页面加载完成

    // const links = await page.$$eval("#content_left .t a", (els) =>
    //   els.map((el) => {
    //     return {
    //       title: el.innerText,
    //       href: el.href,
    //     };
    //   })
    // ); // 获取第一页的文章链接

    const pic = await page.screenshot({
        fullPage: true,
        encoding: 'binary'
    })

    // 关闭标签页
    await page.close(); 

    return pic;
  }

  async close() {
    if (this.browser) {
        await this.browser.close()
    }
  }
}

module.exports = new Browser();
